package com.example.myapplication.ui.inspection;

import android.app.Dialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.myapplication.R;
import com.example.myapplication.service.InspectionService;
import com.rmondjone.locktableview.LockTableView;
import com.rmondjone.xrecyclerview.ProgressStyle;
import com.rmondjone.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class InspectionCheck extends AppCompatActivity implements View.OnClickListener {
    private ImageButton calendarBtn;
    private Dialog bottomDialog;
    private InspectionService inspectionService;
    private DatePicker datePicker;
    private TextView dateTextView;
    private Button searchBtn;
    private TextView classesTextView;
    private TextView categoryTextView;
    private LockTableView inspectionTable;
    private Dialog checkDialog;
    private ArrayList<ArrayList<String>> tableData;
    private Spinner classesSpinner;
    private Spinner equipCategorySpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_inspection_check);
        calendarBtn = findViewById(R.id.calendarBtn);
        dateTextView = findViewById(R.id.inspection_check_date_text);
        searchBtn = findViewById(R.id.inspection_search_button);
        classesTextView = findViewById(R.id.classes_text);
        categoryTextView = findViewById(R.id.category_text);
        classesSpinner = findViewById(R.id.class_spinner);
        equipCategorySpinner = findViewById(R.id.equipment_spinner);

        calendarBtn.setOnClickListener(this);
        searchBtn.setOnClickListener(this);

        setClassSpinnerListener();
        setEquipmentSpinnerListener();
        initInspectionTable();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.calendarBtn:
                showBottomDialog();
                loadDatePicker();
                break;
            case R.id.inspection_search_button:
                refreshInspectionTable();
                break;
        }
    }

    private void loadDatePicker() {
        datePicker = bottomDialog.findViewById(R.id.date_picker_inspection_check);
        initDatePicker();
    }

    private void initDatePicker() {
        String dateText = dateTextView.getText().toString();
        int year = 0;
        int month = 0;
        int day = 0;
        if (dateText.matches("[0-9]+-[0-9]+-[0-9]+")) {
            String[] dates = dateText.split("-");
            if (dates.length == 3) {
                year = Integer.parseInt(dates[0]);
                month = Integer.parseInt(dates[1]) - 1;
                day = Integer.parseInt(dates[2]);
            }
        } else {
            Calendar cal = Calendar.getInstance();
            year = cal.get(cal.YEAR);
            month = cal.get(cal.MONTH);
            day = cal.get(cal.DATE);
        }
        datePicker.init(year, month, day,
                (picker, y, m, d) -> dateTextView.setText(y + "-" + (m + 1) + "-" + d));
    }

    private void showBottomDialog() {
        bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_date_picker, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }

    private void showCheckDialog(List<String> Item) {
        if (Item.size() < 8) {
            return;
        }
        checkDialog = new Dialog(this, R.style.Theme_AppCompat_Light_Dialog);
        View inspectionDetailsView = LayoutInflater.from(this).inflate(R.layout.dialog_inspection_check, null);

        TextView dateText = inspectionDetailsView.findViewById(R.id.date_text);
        dateText.setText(Item.get(1));
        TextView classesText = inspectionDetailsView.findViewById(R.id.classes_text);
        classesText.setText(Item.get(2));
        TextView categoryText = inspectionDetailsView.findViewById(R.id.category_text);
        categoryText.setText(Item.get(3));
        TextView equipmentText = inspectionDetailsView.findViewById(R.id.equipment_text);
        equipmentText.setText(Item.get(4));
        TextView groupText = inspectionDetailsView.findViewById(R.id.group_text);
        groupText.setText(Item.get(5));
        TextView personText = inspectionDetailsView.findViewById(R.id.person_text);
        personText.setText(Item.get(6));
        TextView situationText = inspectionDetailsView.findViewById(R.id.situation_text);
        situationText.setText(Item.get(7));
        TextView abnormalText = inspectionDetailsView.findViewById(R.id.abnormal_text);
        abnormalText.setText(Item.get(8));

        checkDialog.setContentView(inspectionDetailsView);
        ViewGroup.LayoutParams layoutParams = inspectionDetailsView.getLayoutParams();
        layoutParams.width = (int) (0.9 * getResources().getDisplayMetrics().widthPixels);
        inspectionDetailsView.setLayoutParams(layoutParams);
        checkDialog.getWindow().setGravity(Gravity.CENTER);
        checkDialog.getWindow().setWindowAnimations(R.style.Theme_AppCompat_Light_Dialog);
        checkDialog.show();
    }

    private void refreshInspectionTable() {
        tableData = inspectionService.getInspections(
                dateTextView.getText().toString(), classesTextView.getText().toString(),
                categoryTextView.getText().toString());
        inspectionTable.setTableDatas(tableData);
    }

    private void initInspectionTable() {
        inspectionService = new InspectionService();
        LinearLayout table = findViewById(R.id.inspection_table);
        tableData = inspectionService.getInspections(null, null, null);
        inspectionTable = new LockTableView(this, table, tableData);
        inspectionTable.setLockFristColumn(true) //是否锁定第一列
                .setLockFristRow(false) //是否锁定第一行
                .setMaxColumnWidth(400) //列最大宽度
                .setMinColumnWidth(60) //列最小宽度
                //.setColumnWidth(1, 100) //设置指定列文本宽度(从0开始计算,宽度单位dp)
                .setMinRowHeight(20)//行最小高度
                .setMaxRowHeight(60)//行最大高度
                .setTextViewSize(16) //单元格字体大小
                .setCellPadding(15)//设置单元格内边距(dp)
                .setFristRowBackGroudColor(R.color.table_head)//表头背景色
                .setTableHeadTextColor(R.color.beijin)//表头字体颜色
                .setTableContentTextColor(R.color.border_color)//单元格字体颜色
                .setNullableString("N/A") //空值替换值
                .setOnLoadingListener(new LockTableView.OnLoadingListener() {
                    //下拉刷新、上拉加载监听
                    @Override
                    public void onRefresh(final XRecyclerView mXRecyclerView, final ArrayList<ArrayList<String>> mTableDatas) {
                        //如需更新表格数据调用,部分刷新不会全部重绘
                        inspectionTable.setTableDatas(mTableDatas);
                        //停止刷新
                        mXRecyclerView.refreshComplete();
                    }

                    @Override
                    public void onLoadMore(final XRecyclerView mXRecyclerView, final ArrayList<ArrayList<String>> mTableDatas) {
                        // 如需更新表格数据调用,部分刷新不会全部重绘
                        inspectionTable.setTableDatas(mTableDatas);
                        //停止刷新
                        mXRecyclerView.loadMoreComplete();
                        //如果没有更多数据调用
                        mXRecyclerView.setNoMore(true);
                    }
                })
                .setOnItemClickListenter((view, i) -> showCheckDialog(tableData.get(i)))
                .setOnItemSeletor(R.color.dashline_color)//设置Item被选中颜色
                .show(); //显示表格,此方法必须调用
        inspectionTable.getTableScrollView().setPullRefreshEnabled(true);
        inspectionTable.getTableScrollView().setLoadingMoreEnabled(true);
        inspectionTable.getTableScrollView().setRefreshProgressStyle(ProgressStyle.SquareSpin);
    }

    public void setClassSpinnerListener() {
        classesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] classArray = getResources().getStringArray(R.array.classItem);
                classesTextView.setText(classArray[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    public void setEquipmentSpinnerListener() {
        equipCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] equipmentArray = getResources().getStringArray(R.array.equipment_category);
                categoryTextView.setText(equipmentArray[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}